// pages/person/revisePwd/revisePwd.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    inputForm: {
      newPwd: '', // 新密码
      certType: '1', // 证件类型
      identifyImage: '', // 证件base64
      userImage: '', // 人脸base64
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},
  onShow() {
    wx.hideHomeButton()
  },
  submit() {
    wx.showLoading({
      title: '加载中...',
    })
    wx.$API['home/faceAndIdentifyChangePwd'](this.data.inputForm)
      .then((res) => {
        wx.hideLoading()
        let obj = wx.getStorageSync('changePwdStatus') || {}
        wx.setStorageSync('changePwdStatus', {
          ...obj,
          isSkipChangePwd: false,
        })
        wx.showModal({
          title: '提示',
          content: '密码修改成功',
          success(res) {
            wx.switchTab({
              url: '/pages/home/index',
            })
          },
        })
      })
      .catch((error) => {
        wx.hideLoading()
        console.log(error, 'error')
        wx.showModal({
          title: '提示',
          content: error,
          success(res) {},
        })
      })
  },
  viewImage(e) {
    wx.previewImage({
      current: this.data.inputForm[e.target.dataset.image], // 当前显示图片的http链接
      urls: [this.data.inputForm[e.target.dataset.image]], // 需要预览的图片http链接列表
    })
  },
  close(e) {
    this.setData({
      ['inputForm.' + e.target.dataset.image]: '',
    })
  },
  certTypeChange(e) {
    this.setData({
      'inputForm.certType': e.target.dataset.certtype,
    })
  },
  inputChange(e) {
    this.setData({
      'inputForm.newPwd': e.detail.detail.value,
    })
  },
  chooseImage(e) {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera'],
      success: (res) => {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        let size = res.tempFiles[0].size
        if (size >= 1024 * 1024 * 5) {
          wx.showToast({
            title: '请上传5M以内的图片',
            icon: 'none',
          })
          return
        }
        const MAX = 200 * 1024
        let number = 100
        if (MAX < size) {
          number = parseInt((MAX / size) * 100)
        }
        wx.compressImage({
          src: tempFilePaths[0], // 图片路径
          quality: number, // 压缩质量
          success: (comImage) => {
            const fs = wx.getFileSystemManager()
            fs.readFile({
              filePath: comImage.tempFilePath,
              encoding: 'base64',
              position: 0,
              success: (res) => {
                this.setData({
                  ['inputForm.' + e.target.dataset.image]:
                    'data:image/png;base64,' + res.data,
                })
              },
              fail(res) {
                console.error(res)
              },
            })
          },
          fail(error) {
            console.log(error, '压缩图片失败')
          },
        })
        return
      },
    })
  },
})
